<template>
  <div class="sys-pos-container">
    <el-dialog v-model="state.isShowDialog" draggable :close-on-click-modal="false" width="700px">
      <template #header>
        <div style="color: #fff">
          <el-icon size="16" style="margin-right: 3px; display: inline; vertical-align: middle"> <ele-Edit />
          </el-icon>
          <span> {{ props.title }} </span>
        </div>
      </template>
      <div style="display: flex; justify-content: center; margin-top: 30px">
        <el-button type="primary" round @click="handleButtonClick" style="width: 100px; height: 30px">按物料盘点</el-button>
        <el-button type="primary" round @click="handleButtonClick2" style="width: 100px; height: 30px">按库位盘点</el-button>
      </div>
      <!-- 按物料盘点 -->
      <el-form :model="state.ruleForm" ref="ruleFormRef" label-width="auto" class="fl"
        v-if="showModel1 && showModel2 == false">
        <el-form-item label="物料号" prop="materielnum" :rules="[{ required: true, message: '物料号不能为空', trigger: 'blur' }]"
          @click="open">
          <el-input v-model="state.ruleForm.materielnum"></el-input>
        </el-form-item>
      </el-form>
      <!-- 按库位盘点 -->
      <el-form :model="state.ruleForm" ref="ruleformRef" label-width="auto" class="fl"
        v-if="showModel2 && showModel1 == false">
        <el-form-item label="所属仓库" :rules="[{ required: true, message: '所属仓库不能为空', trigger: 'blur' }]">
          <el-select v-model="state.ruleForm.whNum" filterable clearable class="w100"
            @change="handleChange(state.ruleForm.whNum)">
            <el-option v-for="item in state.belongWarehouses" :key="item" :label="item.eg_wms_warehouse.WHName"
              :value="item.eg_wms_warehouse.WHNum" />
          </el-select>
        </el-form-item>
        <el-form-item label="所属区域" prop="regionNum" :rules="[{ required: true, message: '所属区域不能为空', trigger: 'blur' }]">
          <el-select v-model="state.ruleForm.regionNum" filterable clearable class="w100"
            @change="handleRegionchange()">
            <el-option v-for="item in state.belongAreas" :key="item" :label="item.RegionName" :value="item.RegionNum" />
          </el-select>
        </el-form-item>
        <el-form-item label="库位编号" prop="storageNum" :rules="[{ required: true, message: '库位编号不能为空', trigger: 'blur' }]"
          @click="openAdd">
          <el-input v-model="state.ruleForm.storageNum" type="textarea" clearable />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="cancel">取 消</el-button>
          <el-button type="primary" @click="submit">确 定</el-button>
        </span>
      </template>
    </el-dialog>
    <EditOrg ref="editRef" @handleQuery="addValue" :type="state.ruleForm.regionNum" />
    <EditWuliao ref="editRef2" @handleQuery="addMaterialValue" />
  </div>
</template>

<script lang="ts" setup name="sysEditPos">
import { reactive, ref } from 'vue';
import EditWuliao from "/@/views/system/takeInventory/editWuliao.vue";
import EditOrg from "/@/views/system/takeInventory/editKuwei.vue";
import { feature, getAPI } from '/@/utils/axios-utils';
import { APIJSONApi, SysDictDataApi, SysPosApi } from '/@/api-services/api';
import { WmsApi } from '/@/api/wh';
import { ElMessage } from 'element-plus';

const props = defineProps({
  title: String,
});
const editRef = ref();
const editRef2 = ref();
const showModel1 = ref(false);
const showModel2 = ref(false);
const emits = defineEmits(['handleQuery']);
const ruleFormRef = ref();
const ruleformRef = ref();


const state = reactive({
  belongAreas: [],
  isShowDialog: false,
  ruleForm: {},
  belongWarehouses: []
});

// 打开弹窗
const openDialog = async (row: any) => {
  try {
    const res = await feature(
      getAPI(APIJSONApi).apiAPIJSONGetPost({
        "[]": {
          "eg_wms_warehouse": {
            IsDelete: 0,
            "@column": "WHName,WHNum",
          },
        },
      })
    );
    state.belongWarehouses = res[1].data.result["[]"];
  } catch (error) {
    console.log(error);
  }
  state.ruleForm = JSON.parse(JSON.stringify(row));
  state.isShowDialog = true;
  ruleFormRef.value?.resetFields();
};

// 关闭弹窗
const closeDialog = () => {
  emits('handleQuery');
  state.isShowDialog = false;
};
const handleChange = async (id) => {
  state.belongAreas = []; //arr
  try {
    const res = await feature(
      getAPI(APIJSONApi).apiAPIJSONGetPost({
        "[]": {
          "eg_wms_region": {
            IsDelete: 0,
            WHNum: id,
            "@column": "RegionNum,RegionName",
          },
        },
      })
    );

    res[1].data.result["[]"].forEach((item, index, input) => {
      input[index] = item.eg_wms_region;
    });
    state.belongAreas = res[1].data.result["[]"];
  } catch (error) {
    console.log(error);
  }
};
const handleRegionchange = () => {
  state.ruleForm.storageNum = ''
}
const handleButtonClick = () => {
  showModel1.value = true;
  showModel2.value = false;
};
// 按库位盘点
const handleButtonClick2 = () => {
  showModel2.value = true;
  showModel1.value = false;
};
const addValue = (parms) => {
  console.log("我是父组件，我接收到了 " + parms);
  // 处理得到的参数
  let storageNum1 = parms.map((item) => {
    return item.storageNum;
  });
  state.ruleForm.storageNum = storageNum1.join();
  console.log(state.ruleForm.storageNum);
};
const addMaterialValue = (parms) => {
  //得到的参数是一整个对象,拿出物料号
  state.ruleForm.materielnum = parms.map((item) => {
    return item.materielNum;
  });
};
// 取消
const cancel = () => {
  state.isShowDialog = false;
};

// 提交
const submit = () => {
  if (state.ruleForm.storageNum) {
    ruleformRef?.value.validate(async (valid, object) => {
      if (!valid) return false;
      WmsApi()
        .CreateTaskByStorage(state.ruleForm.storageNum,"1")
        .then(function (res) {
          
          ElMessage.success("新增按库位盘点任务成功");
          closeDialog();
        })
        .catch(function (error) {
          console.log(error);
        });
    });
  } else {
    ruleFormRef?.value.validate(async (valid, object) => {
      if (!valid) return false;
      WmsApi()
        .CreateTaskByMaterial({ materielNum: state.ruleForm.materielnum[0]})
        .then(function (res) {
          console.log(res);
          ElMessage.success("新增按物料盘点任务成功");
          closeDialog();
        })
        .catch(function (error) {
          console.log(error);
        });
    });
  }

}
//打开选取组件
const openAdd = () => {
  state.editOrgTitle = "选取库位";
  editRef.value?.openDialog();
};
//打开选取组件
const open = () => {
  state.editOrgTitle = "选取物料";
  editRef2.value?.openDialog();
};

// 导出对象
defineExpose({ openDialog });
</script>
<style lang="scss" scoped>
.fl {
  width: 70%;
  margin: 20px auto;
}
</style>